"""
初始化一个driver
方便每一个页面调用
"""
import logging

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    #收集日志，设置日志级别
    logging.basicConfig(level=logging.INFO)

    def __init__(self, driver:WebDriver = None):
        self.driver = driver

    #封装查找方法
    def find(self, locator):
        logging.info(f'find: {locator}')
        return self.driver.find_element(*locator)

    #封装查找多个元素的方法
    def finds(self, locator):
        logging.info(f'find_elements: {locator}')
        return self.driver.find_elements(*locator)

    #封装查找并点击方法
    def find_and_click(self, locator):
        logging.info('click')
        self.find(locator).click()

    #封装查找并输入
    def find_and_sendkeys(self, locator, text):
        logging.info(f'sendkeys: {text}')
        self.find(locator).send_keys(text)

    #封装滚动查找
    def find_scroll(self, text):
        logging.info('find_scroll')
        return self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR, 'new UiScrollable(new UiSelector().'
                                                               'scrollable(true).instance(0)).'
                                                               f'scrollIntoView(new UiSelector().textContains("{text}").'
                                                               'instance(0));')

    #封装显式等待
    def webdriver_wait(self, locator, timeout=10):
        logging.info(f'webdriver_wait: {locator}, timeout: {timeout}')
        element = WebDriverWait(self.driver, timeout).until(
            lambda x: x.find_element(*locator))
        return element

    # 封装返回操作
    def back(self, num=1):
        logging.info(f'back: {num}')
        for i in range(num):
            self.driver.back()
